package cn.com.transfer.services;

import cn.com.transfer.params.IcbcParams;
import cn.com.transfer.utils.Constants;
import flexjson.JSONSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import static cn.com.transfer.utils.IcbcInfo.isRun;
import static cn.com.transfer.utils.IcbcInfo.schoolId;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 签退
 */
public class SignOut extends MsgHandlerService {
    private Logger logger = LoggerFactory.getLogger(SignOut.class);

    @Override
    public String handler(Map params) {
        Map rtn = new HashMap();
        try {
            Calendar ca = Calendar.getInstance();
            IcbcParams req = new IcbcParams(1);
            req.schoolCode = schoolId;
            req.transCode = Constants.ICBC_TRANS_SIGN_OUT;
            req.transTime = String.format("%02d:%02d:%02d", ca.get(Calendar.HOUR_OF_DAY), ca.get(Calendar.MINUTE), ca.get(Calendar.SECOND));
            req.transDate = String.format("%04d-%02d-%02d", ca.get(Calendar.YEAR), ca.get(Calendar.MONTH) + 1, ca.get(Calendar.DAY_OF_MONTH));
            req.mac = req.genMac(1);

            IcbcParams resp = sendMessage(req);
            /*for (int i = 0; i < 3; i++) {
                resp = sendMessage(req);
                if (resp != null) break;
            }*/
            checkNotNull(resp, "连接服务器失败");
            checkArgument(resp.rtnCode.equals("00000"), resp.rtnMsg == null ? (String) Constants.msgMap.get(resp.rtnCode) : resp.rtnMsg);

            isRun = false;
            rtn.put("success", true);
            logger.info("签退成功");
        } catch (Exception e) {
            logger.error("error in signOut", e);
            rtn.put("success", false);
            rtn.put("msg", e.getMessage() != null ? e.getMessage() : e.toString());
        }

        return new JSONSerializer().serialize(rtn);
    }
}
